const fs = require('fs')
const path = require('path')

async function generateUtilsIndex() {
  const dir = path.resolve(__dirname, '../utils')
  const indexPath = path.join(dir, 'index.js')

  if (!fs.existsSync(dir)) return

  const files = fs.readdirSync(dir)
    .filter(file => file.endsWith('.js') && file !== 'index.js')

  const exportLines = files.map(file => {
    const name = file.replace(/\.js$/, '')
    return `export * from './${name}';`
  })

  fs.writeFileSync(indexPath, exportLines.join('\n') + '\n')
  console.log(`✅ 已生成 utils/index.js 推荐使用@zzcpt/zztool`)
}

async function generateComponentsIndex() {
  const dir = path.resolve(__dirname, '../components')
  const indexPath = path.join(dir, 'index.js')

  if (!fs.existsSync(dir)) return

  const entries = fs.readdirSync(dir)
  const exportLines = []

  for (const entry of entries) {
    if (entry === 'index.js') continue

    const fullPath = path.join(dir, entry)
    const stat = fs.statSync(fullPath)

    if (stat.isDirectory()) {
      const vuePath = path.join(fullPath, 'index.vue')
      const jsPath = path.join(fullPath, 'index.js')
      const jsxPath = path.join(fullPath, 'index.jsx')
      const baseName = entry

      if (fs.existsSync(vuePath)) {
        exportLines.push(`export { default as ${baseName} } from './${baseName}/index.vue';`)
      } else if (fs.existsSync(jsPath)) {
        exportLines.push(`export { default as ${baseName} } from './${baseName}/index.js';`)
      } else if (fs.existsSync(jsxPath)) {
        exportLines.push(`export { default as ${baseName} } from './${baseName}/index.jsx';`)
      }
    } else if (entry.endsWith('.vue')) {
      const name = entry.replace(/\.vue$/, '')
      exportLines.push(`export { default as ${name} } from './${name}.vue';`)
    }
  }

  fs.writeFileSync(indexPath, exportLines.join('\n') + '\n')
  console.log(`✅ 已修复并生成 components/index.js`)
}

async function generateSharedIndex() {
  const sharedPath = path.resolve(__dirname, '../index.js')
  fs.writeFileSync(sharedPath, `export * from './utils';\nexport * from './components';\n`)
  console.log(`✅ 已生成 shared/index.js`)
}

// 运行入口
main()
async function main() { 
  await generateComponentsIndex()
  await generateSharedIndex()
  await generateUtilsIndex()
}
